<?php
declare (strict_types = 1);

namespace app\admin\controller;
use \app\common\model\Content as Model;
class Content extends AdminBase
{
    protected function initialize()
    {
        parent::initialize();
        $this->model = new Model;
        $this->validate = new \app\common\validate\Content;
        $this->order = 'id desc';
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $where = [];
        // 自定义搜索
        if(method_exists($this, 'searchConditionHandle')){
            $this->searchConditionHandle($where);
        }
        // 排序字段
        $sort_by = $this->request->param('sort/s', $this->model->getPk());
        // 升序/降序
        $desc = $this->request->param('descending/s', 'true');
        // 分页容量
        $page_size = $this->request->param('page_size/d',$this->page_size);

        if($this->request->param('trashed/s', 'false') === 'true'){
            $result = $this->model->onlyTrashed()->where($where)->order($desc === 'true' ? $sort_by.' desc' : $sort_by)->paginate($page_size);
        }else{
            $result = $this->model->where($where)->order($desc === 'true' ? $sort_by.' desc' : $sort_by)->paginate($page_size);
        }
        return json($result);
    }
    // 设置搜索条件
    protected function searchConditionHandle(&$where)
    {
        $search = $this->request->param('search',null);
        if($search) {
            $search = json_decode($search, true);
            if(is_array($search) && sizeof($search) > 0) {
                ((array_key_exists('id', $search) && !empty($search['id'])) && $where[] = ['id','=', $search['id']]);
                ((array_key_exists('title', $search) && !empty($search['title'])) && $where[] = ['title','like', '%'.$search['title'].'%']);
                ((array_key_exists('status', $search) && !empty($search['status'])) && $where[] = ['status','=', $search['status']]);
                ((array_key_exists('category', $search) && !empty($search['category'])) && $where[] = ['category', '=', $search['category'][0]]);
            }
        }
    }
    /**
     * 恢复单条数据
     *
     * @return void
     */
    public function restore(){
        $this->setAllowMethod(['put']);
        $id = $this->request->param('id', null);
        if ($id === null) return json('参数错误！',500);
        $data = $this->model->onlyTrashed()->where($this->model->getPk(),$id)->find();
        if(empty($data) || empty($id)){
            return json('未找到数据！',500);
        }
        $data->restore();
        return json('恢复成功！');
    }
    // 首页数据展示
    public function statistics(){
        $res = $this->model->getStatistics();
        return json($res);
    }
    public function status_count(){
        $res = $this->model->getStatusCount();
        return json($res);
    }
    // 数据导出
    public function export() {
        return json('', 404);
    }
}
